package com.xgq.drink.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xgq.drink.annotation.RequiresRole;
import com.xgq.drink.entity.OrderProduct;
import com.xgq.drink.entity.Orders;
import com.xgq.drink.entity.Product;
import com.xgq.drink.entity.R;
import com.xgq.drink.entity.dto.CompositeOrderQuery;
import com.xgq.drink.service.IAddressService;
import com.xgq.drink.service.IOrderProductService;
import com.xgq.drink.service.IOrderService;
import com.xgq.drink.service.IProductService;
import com.xgq.drink.utils.JwtTokenUtil;
import com.xgq.drink.utils.RUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/order")
@Tag(name = "订单模块", description = "订单相关接口")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderProductService orderProductService;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping("/create")
    @Operation(summary = "创建订单", description = "用户创建新订单",
            responses = {
                    @ApiResponse(responseCode = "200", description = "订单创建成功",
                            content = @Content(schema = @Schema(implementation = R.class))),
                    @ApiResponse(responseCode = "400", description = "订单创建失败",
                            content = @Content(schema = @Schema(implementation = R.class)))
            })
    public R createOrder(@RequestBody List<Product> products,@RequestParam Long addressId,HttpServletRequest request) {
        System.out.println("--------------");
        System.out.println(products);
        try {
            List<Orders> createdOrder = orderService.saveOrder(products,jwtTokenUtil.getUserIdFromRequest(request),addressId);
            return RUtils.success("订单创建成功", createdOrder);
        } catch (Exception e) {
            return RUtils.fail("订单创建失败: " + e.getMessage());
        }
    }

    @GetMapping("/list")
    @Operation(summary = "分页查询订单", description = "根据分页参数和订单状态查询订单列表",
            responses = {
                    @ApiResponse(responseCode = "200", description = "查询成功",
                            content = @Content(schema = @Schema(implementation = IPage.class))),
                    @ApiResponse(responseCode = "400", description = "查询失败",
                            content = @Content(schema = @Schema(implementation = R.class)))
            })
    public R getOrderList(@RequestParam(defaultValue = "1") int current,
                                        @RequestParam(defaultValue = "10") int size,
                                        @RequestParam(required = false) String status) {
        try {
            IPage<Orders> orderList = orderService.getOrderList(current, size, status);
            return RUtils.success("查询成功", orderList);
        } catch (Exception e) {
            return RUtils.fail("查询失败: " + e.getMessage());
        }
    }
    @GetMapping("/list/user")
    @Operation(summary = "按状态查询用户订单")
    public R getOrdersByStatusForUser(
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request) {
        // 从token解析用户ID
        String token = request.getHeader("Authorization");
        Long userId = Long.parseLong(jwtTokenUtil.getUserIdFromToken(token));
        System.out.println("状态");
        System.out.println(status);
        System.out.println(userId);
        try {
            IPage<Orders> orderList = orderService.getUserOrderList(
                    userId,
                    current,
                    size,
                    status
            );
            for (Orders order : orderList.getRecords()) {
                System.out.println(order);
                QueryWrapper<OrderProduct> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("order_id", order.getOrderId());
                order.setOrderProducts(
                        orderProductService.list(queryWrapper)
                );
                order.setAddressInfo(addressService.getById(order.getAddress()));
            }
            return RUtils.success("查询成功", orderList);
        } catch (Exception e) {
            return RUtils.fail("查询失败: " + e.getMessage());
        }
    }
    @GetMapping("/composite")
    @Operation(summary = "复合订单查询", description = "支持多条件查询并返回完整订单数据")
    public R getCompositeOrders(
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
            @RequestParam(required = false) BigDecimal minAmount,
            @RequestParam(required = false) BigDecimal maxAmount,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String orderId,
            @RequestParam(required = false) Long productId,
            @RequestParam(required = false) String category,
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request) {

        try {
            // 构建查询参数
            CompositeOrderQuery query = new CompositeOrderQuery();
            String token = request.getHeader("Authorization");
            Long brandId = jwtTokenUtil.getStoreIdFromToken(token);
            query.setBrandId(brandId)
                    .setStatus(status)
                    .setStartTime(startTime)
                    .setEndTime(endTime)
                    .setMinAmount(minAmount)
                    .setMaxAmount(maxAmount)
                    .setUserId(userId)
                    .setOrderId(orderId)
                    .setProductId(productId)
                    .setCategory(category)
                    .setCurrent(current)
                    .setSize(size);

            IPage<Orders> result = orderService.getCompositeOrders(query);
            return RUtils.success("复合查询成功", result);
        } catch (Exception e) {
            return RUtils.fail("复合查询失败: " + e.getMessage());
        }
    }

    @PutMapping("/update")
    @Operation(summary = "修改订单信息", description = "仅支持修改地址和退款信息",
            responses = {
                    @ApiResponse(responseCode = "200", description = "修改成功",
                            content = @Content(schema = @Schema(implementation = Orders.class))),
                    @ApiResponse(responseCode = "400", description = "修改失败",
                            content = @Content(schema = @Schema(implementation = R.class)))
            })
    public R updateOrder(@RequestBody Orders order) {
        try {
            Orders updatedOrder = orderService.updateOrder(order);
            return RUtils.success("订单修改成功", updatedOrder);
        } catch (Exception e) {
            return RUtils.fail("订单修改失败: " + e.getMessage());
        }
    }

    @PutMapping("/cancel")
    @Operation(summary = "取消订单", description = "用户取消未发货的订单，并记录取消原因",
            responses = {
                    @ApiResponse(responseCode = "200", description = "订单取消成功",
                            content = @Content(schema = @Schema(implementation = R.class))),
                    @ApiResponse(responseCode = "400", description = "订单取消失败",
                            content = @Content(schema = @Schema(implementation = R.class)))
            })
    public R cancelOrder(@RequestBody Orders order, @RequestParam String reason, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            Long userId = Long.parseLong(jwtTokenUtil.getUserIdFromToken(token));
            order.setUserId(userId);
            orderService.cancelOrder(order, reason);
            return RUtils.success("订单取消中");
        } catch (Exception e) {
            return RUtils.fail("订单取消失败: " + e.getMessage());
        }
    }
    @PutMapping("/confirmReceipt")
    @Operation(summary = "用户确认收货", description = "用户确认收货，更新订单状态为待评价",
            responses = {
                    @ApiResponse(responseCode = "200", description = "确认收货成功",
                            content = @Content(schema = @Schema(implementation = R.class))),
                    @ApiResponse(responseCode = "400", description = "确认收货失败",
                            content = @Content(schema = @Schema(implementation = R.class)))
            })
    public R confirmReceipt(@RequestParam Long orderId, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            Long userId = Long.parseLong(jwtTokenUtil.getUserIdFromToken(token));
            orderService.confirmReceipt(orderId, userId);
            return RUtils.success("确认收货成功");
        } catch (Exception e) {
            return RUtils.fail("确认收货失败: " + e.getMessage());
        }
    }
    @PutMapping("/refund")
    @Operation(summary = "申请退货", description = "用户申请退货，并记录退货原因",
            responses = {
                    @ApiResponse(responseCode = "200", description = "退货申请成功",
                            content = @Content(schema = @Schema(implementation = R.class))),
                    @ApiResponse(responseCode = "400", description = "退货申请失败",
                            content = @Content(schema = @Schema(implementation = R.class)))
            })
    public R refundOrder(@RequestBody Orders order, @RequestParam String reason, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            Long userId = Long.parseLong(jwtTokenUtil.getUserIdFromToken(token));
            order.setUserId(userId);
            orderService.refundOrder(order, reason);
            return RUtils.success("退货申请成功");
        } catch (Exception e) {
            return RUtils.fail("退货申请失败: " + e.getMessage());
        }
    }

    @GetMapping("/list/brand")
    @RequiresRole(value = {"STORE_OWNER", "STORE_STAFF"}, brandRequired = true)
    @Operation(summary = "按状态查询品牌订单")
    public R getOrdersByStatus(
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
            @RequestParam(required = false) BigDecimal minAmount,
            @RequestParam(required = false) BigDecimal maxAmount,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String orderId,
            @RequestParam(required = false) Long productId,
            @RequestParam(required = false) String category,
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Long brandId = jwtTokenUtil.getStoreIdFromToken(token);
        try {
            IPage<Orders> orderList = orderService.getBrandOrderList(
                    brandId,
                    status,
                    current,
                    size
            );
            return RUtils.success("查询成功", orderList);
        } catch (Exception e) {
            return RUtils.fail("查询失败: " + e.getMessage());
        }
    }

    @PutMapping("/status/brand")
    @RequiresRole(value = {"STORE_OWNER", "STORE_STAFF"}, brandRequired = true)
    @Operation(summary = "修改订单状态")
    public R updateOrderStatus(
            @RequestParam Long orderId,
            @RequestParam Integer newStatus,
            HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            Long brandId = jwtTokenUtil.getStoreIdFromToken(token);
            // 添加状态校验
            if (newStatus == 7) {
                Orders existing = orderService.getById(orderId);
                if (existing.getStatus() != 5) {
                    return RUtils.fail("只有退款中的订单可以执行此操作");
                }
            }
            Orders order = new Orders();
            order.setOrderId(orderId);
            order.setStatus(newStatus);
            Orders updatedOrder = orderService.updateOrderStatus(order);

            return RUtils.success("状态更新成功", updatedOrder);
        } catch (Exception e) {
            return RUtils.fail("状态更新失败: " + e.getMessage());
        }
    }

    
}